package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.NumberUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.CacheConstants;
import com.zzyl.dto.AlertNotifyDto;
import com.zzyl.dto.AlertRuleDto;
import com.zzyl.entity.AlertData;
import com.zzyl.entity.AlertRule;
import com.zzyl.mapper.AlertDataMapper;
import com.zzyl.mapper.AlertRuleMapper;
import com.zzyl.mapper.DeviceMapper;
import com.zzyl.mapper.UserRoleMapper;
import com.zzyl.service.AlertRuleService;
import com.zzyl.service.UserService;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.utils.StringUtils;
import com.zzyl.vo.AlertRuleVo;
import com.zzyl.vo.DeviceDataVo;
import com.zzyl.webSocket.WebSocketServer;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author sjqn
 */
@Slf4j
@Service
public class AlertRuleServiceImpl implements AlertRuleService {

    @Autowired
    private AlertRuleMapper alertRuleMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private AlertDataMapper alertDataMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;

    /**
     * 新增报警规则
     *
     * @param alertRuleDto 报警规则请求模型
     */
    @Override
    public void createRule(AlertRuleDto alertRuleDto) {
        AlertRule alertRule = BeanUtil.toBean(alertRuleDto, AlertRule.class);
        alertRuleMapper.insert(alertRule);
    }

    /**
     * 分页条件查询
     *
     * @param pageNum       页码
     * @param pageSize      页面大小
     * @param alertRuleName 报警规则名称
     * @param productKey    产品key
     * @param functionName  功能名称
     * @return 分页结果
     */
    @Override
    public PageResponse<AlertRuleVo> getAlertRulePage(Integer pageNum, Integer pageSize, String alertRuleName, String productKey, String functionName) {
        PageHelper.startPage(pageNum, pageSize);
        Page<AlertRuleVo> page = alertRuleMapper.page(alertRuleName, productKey, functionName);
        //添加提示
        page.getResult().forEach(alertRuleVo -> {
            String alertReason = CharSequenceUtil.format("{}{}{},持续{}个周期就报警", alertRuleVo.getFunctionName(), alertRuleVo.getOperator(), alertRuleVo.getValue(), alertRuleVo.getDuration());
            alertRuleVo.setRules(alertReason);
        });

        return PageResponse.of(page, AlertRuleVo.class);
    }

    /**
     * 删除报警
     *
     * @param id 报警规则id
     */
    @Override
    public void deleteAlertRule(Long id) {
        alertRuleMapper.deleteByPrimaryKey(id);
    }

    /**
     * 修改报警
     *
     * @param id           报警规则id
     * @param alertRuleDto 报警规则更新请求模型
     */
    @Override
    public void updateAlertRule(Long id, AlertRuleDto alertRuleDto) {
        AlertRule alertRule = BeanUtil.toBean(alertRuleDto, AlertRule.class);
        alertRuleMapper.updateByPrimaryKeySelective(alertRule);
    }

    /**
     * 查询报警信息
     *
     * @param id 报警规则id
     * @return 报警信息
     */
    @Override
    public AlertRuleVo readAlertRule(Long id) {
        AlertRule alertRule = alertRuleMapper.selectByPrimaryKey(id);
        return BeanUtil.toBean(alertRule, AlertRuleVo.class);
    }

    /**
     * 启用或禁用
     *
     * @param id     报警id
     * @param status 报警规则状态
     */
    @Override
    public void enableOrDisable(Long id, Integer status) {
        alertRuleMapper.updateStatus(id, status);
    }

    /**
     * 数据报警处理 进行报警规则过滤
     */
    @Override
    public void alertFilter(DeviceDataVo deviceDataVo) {
        //获取设备上报数据时间，如果上报发生在1分钟前，为历史数据，不在处理
        deviceDataVo.getAlarmTime();
        long between = LocalDateTimeUtil.between(deviceDataVo.getAlarmTime(), LocalDateTime.now(), ChronoUnit.SECONDS);
        if (between > 60) {
            return;
        }

        //准备对应报警规则数据
        //查询所有规则
        List<AlertRule> allAlertRules = alertRuleMapper.selectByFunctionId(deviceDataVo.getFunctionId(), "-1", deviceDataVo.getProductKey());
        //查询此设备的规则
        List<AlertRule> theAlertRules = alertRuleMapper.selectByFunctionId(deviceDataVo.getFunctionId(), deviceDataVo.getIotId(), deviceDataVo.getProductKey());
        //如果报警规则不为空，遍历报警规则，进行校验
        Collection<AlertRule> alertRules = CollUtil.addAll(theAlertRules, allAlertRules);
        if (CollUtil.isEmpty(alertRules)) {
            return;
        }
        alertRules.forEach(alertRule -> {
            deviceDateAlarmHandler(deviceDataVo, alertRule);
        });


    }

    @Value("${zzyl.alert.deviceMaintainerRole}")
    private String deviceMaintainerRole;
    @Value("${zzyl.alert.managerRole}")
    private String managerRole;

    /**
     * 设备数据报警处理器
     *
     * @param deviceDataVo 设备上报数据
     * @param alertRule    报警规则
     */
    private void deviceDateAlarmHandler(DeviceDataVo deviceDataVo, AlertRule alertRule) {
        //第一层校验  判断是否在报警时间范围内
        String[] split = alertRule.getAlertEffectivePeriod().split("~");
        LocalTime start = LocalTime.parse(split[0]);
        LocalTime end = LocalTime.parse(split[1]);
        LocalTime localTime = LocalDateTimeUtil.of(deviceDataVo.getAlarmTime()).toLocalTime();
        if (localTime.isAfter(end) || localTime.isBefore(start)) {
            return;
        }
        //设备id
        String iotId = deviceDataVo.getIotId();
        //从redis中获取数据，报警规则连续触发次数rediskey
        String aggCountKey = CacheConstants.ALERT_TRIGGER_COUNT_PREFIX +
                iotId + ":" + deviceDataVo.getFunctionId() + ":" + alertRule.getId();
        //第二层校验：将设备上报值和阈值比较
        //x – 第一个值，y – 第二个值。x==y返回0，x<y返回小于0的数，x>y返回大于0的数
        int compare = NumberUtil.compare(Float.parseFloat(deviceDataVo.getDataValue()), alertRule.getValue());
        if (compare >= 0 && alertRule.getOperator().equals(">=") ||
                compare < 0 && alertRule.getOperator().equals("<")) {
            log.info("设备上报数据大于等于阈值，符合报警规则");
        }else {
            //该情况不符合报警规则，所以设备上报数据为正常数据。需要删除redis聚合的异常数据,程序结束
            redisTemplate.delete(aggCountKey);
            return;
        }
        //第三层校验  判断是否在静默时间范围内
        String silentCacheKey = CacheConstants.ALERT_SILENT_PREFIX + iotId + ":" + deviceDataVo.getFunctionId() + ":" + alertRule.getId();
        String s = redisTemplate.opsForValue().get(silentCacheKey);
        if (!StringUtils.isEmpty(s)) {
            //如果redis中存在该沉默缓存，则说明在沉默时间范围内，直接返回
            return;
        }
        //第四层校验 校验持续周期
        //4.1获取连续触发报警规则的次数
        //aggCountData是上次触发报警累计到的次数，这一次又触发了报警，所以累积到这次就+1

        Integer aggCountData = redisTemplate.opsForValue().get(aggCountKey) == null ? 1 : Integer.parseInt(redisTemplate.opsForValue().get(aggCountKey)) + 1;

        //4.2判断次数是否与持续周期相等
        //如果触发报警规则次数不等于持续周期，则无需报警
        if(!aggCountData.equals(alertRule.getDuration())){
            redisTemplate.opsForValue().set(aggCountKey, aggCountData.toString());
        }else{
            //如果触发报警规则次数等于持续周期，则需要报警，完成以下操作：
            //1）删除报警规则连续触发次数的缓存
            redisTemplate.delete(aggCountKey);
            //2）添加对应的沉默周期，设置过期时间添加对应的沉默周期，设置过期时间
            redisTemplate.opsForValue().set(silentCacheKey, deviceDataVo.getDataValue(), alertRule.getAlertSilentPeriod(), TimeUnit.MINUTES);
            //3）报警数据存储到数据库
            List<Long> allConsumerIds = null;

            if(alertRule.getAlertDataType().equals(0)){
                //随身设备 老人
                if(deviceDataVo.getLocationType().equals(0)){
                    //老人 随身
                    allConsumerIds = deviceMapper.selectNursingIdsByIotIdWithElder(iotId);
                }else {
                    allConsumerIds = deviceMapper.selectNursingIdsByIotIdWithBed(iotId);
                }
            }else{
                //固定设备
                allConsumerIds = userRoleMapper.selectByRoleName(deviceMaintainerRole);
            }
            List<Long> list = userRoleMapper.selectByRoleName(managerRole);
            // 报警信息推送的所有人id
            allConsumerIds= CollUtil.addAllIfNotContains(allConsumerIds, list);


            // 报警信息推送给客户端
            //保存报警数据
            List<AlertData> list1 = insertAlertData(deviceDataVo, alertRule, allConsumerIds);

            //获取需要推送的用户id列表

            List<Long> userIds = list1.stream().map(AlertData::getUserId).collect(Collectors.toList());
            //发送websocket消息
            websocketNotify(alertRule, list1.get(0), userIds);
        }
    }

    @Autowired
    private WebSocketServer webSocketServer;
    /**
     * 发送websocket消息
     * @param alertRule
     * @param alertData
     * @param userIds
     */
    private void websocketNotify(AlertRule alertRule, AlertData alertData, List<Long> userIds) {
        AlertNotifyDto alertNotifyDto = BeanUtil.toBean(alertData, AlertNotifyDto.class);
        alertNotifyDto.setFunctionName(alertRule.getFunctionId());
        alertNotifyDto.setAlertDataType(alertData.getType());
        alertNotifyDto.setNotifyType(1);

        //给指定消费者发送消息
        webSocketServer.sendMessageToConsumer(alertNotifyDto, userIds);


    }

    /**
     * 新增报警数据
     *
     * @param deviceDataVo
     * @param alertRule
     * @param allConsumerIds
     */
    private List<AlertData> insertAlertData(DeviceDataVo deviceDataVo, AlertRule alertRule, List<Long> allConsumerIds) {
        String alertReason = CharSequenceUtil.format("{}{}{},持续{}个周期就报警", alertRule.getFunctionName(), alertRule.getOperator(), alertRule.getValue(), alertRule.getDuration());
        AlertData alertData = BeanUtil.toBean(deviceDataVo, AlertData.class);
        alertData.setAlertRuleId(alertRule.getId());
        alertData.setAlertReason(alertReason);
        alertData.setType(alertRule.getAlertDataType());
        alertData.setStatus(0);

        List<AlertData> list = allConsumerIds.stream().map(id -> {
            AlertData dbAlertData = BeanUtil.toBean(alertData, AlertData.class);
            dbAlertData.setUserId(id);
            return dbAlertData;
        }).collect(Collectors.toList());
        alertDataMapper.batchInsert(list);
        return list;
    }


}
